// pages/mine/order/detail.js
const App = getApp()
import Util from '../../../utils/util'

import Kits from '../../../utils/kits'

Page({
  data: {
    init: false,
    order: {},

    change: false,
    cstep: 1,
    selDate: '',
    changePamt: '',
    minDate: undefined,
    curDate: undefined,
    filter(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 30 === 0);
      }
      return options;
    },
    showTimeLine: false,
    hcMaxDate: undefined,
    billchangep: false
  },
  onLoad(options) {
    wx.sub('ReloadUserOrderList', this, () => {
      this.execLoad(this.data.order.id)
    })
    wx.sub('ReloadPayState', this, () => {
      this.execLoad(this.data.order.id)
    })

    this.execLoad(options.oid)
  },
  onUnload() {
    wx.cancel('ReloadPayState', this)
    wx.cancel('ReloadUserOrderList', this)
  },
  execLoad(oid) {
    App.doPost({
      uri: '/app/order/info/detail',
      body: {
        id: oid
      },
      fnSucc: resp => {
        resp.data.deposit.totalStr = Kits.fmtMoneyString(resp.data.deposit.total)
        resp.data.deposit.fineStr = Kits.fmtMoneyString(resp.data.deposit.fine)
        resp.data.deposit.refundStr = Kits.fmtMoneyString(resp.data.deposit.refund)
        resp.data.deposit.vosStr = Kits.fmtMoneyString(resp.data.deposit.total - resp.data.deposit.refund - resp.data.deposit.fine)

        resp.data.rent.totalStr = Kits.fmtMoneyString(resp.data.rent.total)
        resp.data.rent.paidStr = Kits.fmtMoneyString(resp.data.rent.paid)
        resp.data.rent.dayStr = Kits.fmtMoneyString(resp.data.rent.day)
        resp.data.rent.carStr = Kits.fmtMoneyString(resp.data.rent.car)
        resp.data.rent.adjustStr = Kits.fmtMoneyString(resp.data.rent.adjust)
        resp.data.rent.couponStr = Kits.fmtMoneyString(resp.data.rent.coupon)
        resp.data.rent.realStr = Kits.fmtMoneyString(resp.data.rent.real)
        resp.data.rent.pamtStr = Kits.fmtMoneyString(resp.data.rent.real - resp.data.rent.paid)

        const newBills = []
        if(resp.data.bills && Array.isArray(resp.data.bills)){
          resp.data.bills.forEach(bill=>{
            if(bill.createTime){
              bill.createTime = this.formatCurrentYearTime(bill.createTime)
            }
            if(bill.finishTime){
              if(bill.finishTime === '0001-01-01T00:00:00Z'){
                bill.finishTime = ''
              }else{
                bill.finishTime = this.formatCurrentYearTime(bill.finishTime)
              }
            }
            const findNewBillIndex = newBills.findIndex(nBill=>nBill.type === bill.type)
            if(findNewBillIndex > -1){
              const billItem = newBills[findNewBillIndex]
              if(billItem.begin && billItem.close){
                billItem.begin = billItem.begin > bill.begin ? bill.begin : billItem.begin
                billItem.close = billItem.close < bill.close ? bill.close : billItem.close
              }
              newBills[findNewBillIndex].amount = Number(billItem.amount) + Number(bill.amount)
              if(bill.originalAmount){
                newBills[findNewBillIndex].originalAmounttotal = Number(newBills[findNewBillIndex].originalAmounttotal || 0) + Number(bill.originalAmount / 100)
              }else{
                newBills[findNewBillIndex].originalAmounttotal = Number(newBills[findNewBillIndex].originalAmounttotal) + Number(bill.amount)
              }
            }else{
              newBills.push({
                ...bill,
                originalAmounttotal: 
                bill.originalAmount ? Number(bill.originalAmount / 100) : Number(bill.amount)
              })
            }
          })
        }

        const formatTimes = ()=>{
          // 时间轴
          const timelines = []
          if(resp.data.times){
            if(resp.data.times.delivery){
              timelines.push({
                time: resp.data.times.delivery,
                timeStr: this.formatCurrentYearTimeSencord(resp.data.times.delivery),
                title: '交车时间'
              })
            }
            if(resp.data.times.finish){
              timelines.push({
                time: resp.data.times.finish,
                timeStr: this.formatCurrentYearTimeSencord(resp.data.times.finish),
                title: '订单完成时间'
              })
            }
          }
          if(resp.data.deposit.part){
            timelines.push({
              time: resp.data.deposit.part,
              timeStr: this.formatCurrentYearTimeSencord(resp.data.deposit.part),
              title: '车辆押金退款'
            })
          }
          if(resp.data.deposit.full){
            timelines.push({
              time: resp.data.deposit.full,
              timeStr: this.formatCurrentYearTimeSencord(resp.data.deposit.full),
              title: '违章押金退款'
            })
          }
          if(resp.data.times.cancel){
            timelines.push({
              time: resp.data.times.cancel,
              timeStr: this.formatCurrentYearTimeSencord(resp.data.times.cancel),
              title: '订单取消时间'
            })
          }
          if(resp.data.times.paid){
            timelines.push({
              time: resp.data.times.paid,
              timeStr: this.formatCurrentYearTimeSencord(resp.data.times.paid),
              title: '付款时间'
            })
          }
          if(resp.data.times.create){
            resp.data.times.createStr = this.formatCurrentYearTimeSencord(resp.data.times.create)
          }

          // 按时间排序
          timelines.sort((a,b)=>{
            return new Date(a.time).getTime() - new Date(b.time).getTime() > 0 ? -1 : 1
          })
          resp.data.timelines = timelines
          console.log('timelines', timelines)
          resp.data.beginStr = this.formatCurrentYearTime(resp.data.begin)
          resp.data.closeStr = this.formatCurrentYearTime(resp.data.close)
        }
        formatTimes()

        newBills.forEach(item=>{
          if(item.begin && item.close){
            // 计算出天数
            const begin = new Date(item.begin)
            const close = new Date(item.close)
            const days = (close.getTime() - begin.getTime()) / (1000 * 60 * 60 * 24)
            item.days = Math.ceil(days)
            // 平均每天的金额
            item.avgPrice = (item.amount / item.days).toFixed(2)
          }
        })
        resp.data.newBills = newBills

        this.setData({
          init: true,
          order: resp.data,
        })
      }
    })
  },
  doShowBillChange() {
    this.setData({
      billchangep: true
    })
  },
  doHideBillChange() {
    this.setData({
      billchangep: false
    })
  },
  showTimeLineMet() {
    this.setData({
      showTimeLine: !this.data.showTimeLine
    })
  },
  formatCurrentYearTime (time) {
    const date = new Date(time)
    const now = new Date()
    if (date.getFullYear() === now.getFullYear()) {
      return date.format('MM-dd HH:mm')
    } else {
      return date.format('yyyy-MM-dd HH:mm')
    }
  },
  formatCurrentYearTimeSencord (time) {
    const date = new Date(time)
    const now = new Date()
    if (date.getFullYear() === now.getFullYear()) {
      return date.format('MM-dd HH:mm:ss')
    } else {
      return date.format('yyyy-MM-dd HH:mm:ss')
    }
  },
  // 去下单
  toCreate() {
    let now = Kits.getNextTime(new Date().getTime())
    let order = this.data.order
    wx.redirectTo({
      url: `/pages/order/create?carid=${order.car.id}&begin=${now.getTime()}&close=${now.addDays(2).getTime()}&onsite=&onsite_area=&onsite_locs=&onsite_addr=`,
    })
  },
  toMap(e) {
    let locs = e.currentTarget.dataset.locs
    let name = e.currentTarget.dataset.name
    let addr = e.currentTarget.dataset.addr
    if (locs == '') {
      return
    }
    wx.openLocation({
      longitude: parseFloat(locs.split(",")[0]),
      latitude: parseFloat(locs.split(",")[1]),
      scale: 18,
      name: name,
      address: addr
    })
  },
  // 去支付
  toPayment(e) {
    let biz = e.currentTarget.dataset.biz
    let total = 0
    if (biz == 'Rent') {
      total = this.data.order.rent.real
    } else if (biz == 'Deposit') {
      total = this.data.order.deposit.total
    } else if (biz == 'Supp') {
      total = this.data.order.rent.real - this.data.order.rent.paid
    } else if (biz == 'Extend') {
      total = this.data.order.rent.real - this.data.order.rent.paid
    }
    if (total <= 0) {
      return
    }
    let info = {
      id: this.data.order.id,
      expire: 900,
      total: total
    }
    wx.navigateTo({
      url: `/pages/order/pay?src=detail&biz=${biz}&info=${ JSON.stringify(info) }`,
    })
  },
  doShowChange() {
    this.setData({
      minDate: Kits.parseDatetime(this.data.order.close + ":00").getTime() + 30 * 60 * 1000,
      curDate: Kits.parseDatetime(this.data.order.close + ":00").getTime() + 24 * 60 * 60 * 1000,
      cstep: 1,
      change: true,
      hcMaxDate: Kits.parseDatetime(this.data.order.close + ":00").getTime() + 180 * 24 * 60 * 60 * 1000,
    })
  },
  doHideChange() {
    this.setData({
      change: false
    })
  },
  doNextChange(e) {
    let ctime = new Date(e.detail).format('yyyy-MM-dd HH:mm')
    this.setData({
      loading: true,
    })
    App.doPost({
      uri: '/app/order/action/relet',
      body: {
        id: this.data.order.id,
        close: ctime + ":00",
        ask: true
      },
      fnSucc: resp => {
        this.setData({
          cstep: 2,
          selDate: ctime,
          changePamt: Kits.fmtMoneyString(resp.data.pamt)
        })
      },
      funComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },

  doSubmitChange() {

    App.doPost({
      uri: '/app/order/action/relet',
      body: {
        id: this.data.order.id,
        close: this.data.selDate + ":00",
        ask: false
      },
      fnSucc: (resp) => {
        this.setData({
          change: false
        })
        if (resp.data.pamt > 0) {
          wx.showModal({
            title: '续租成功',
            cancelText: '以后再说',
            confirmText: '现在支付',
            content: `是否支付续租租金？`,
            success: (res) => {
              if (res.confirm) {
                let info = {
                  id: this.data.order.id,
                  expire: 900,
                  total: resp.data.pamt
                }
                wx.navigateTo({
                  url: `/pages/order/pay?src=detail&biz=Extend&info=${ JSON.stringify(info) }`,
                })
              }
            }
          })

        } else {
          Util.Toast.succ(`续租订单成功`)
        }
        this.execLoad(this.data.order.id)

      }

    })
  },

  doBuyService() {
    Util.Notify.warn(`当前状态暂不支持购买`)
  },
  doCancel() {
    App.doPost({
      uri: '/app/order/action/cancel/ask',
      body: {
        id: this.data.order.id
      },
      fnSucc: resp => {
        wx.showModal({
          title: '取消提示',
          cancelText: '点错了',
          confirmText: '确认取消',
          confirmColor: '#e54d42',
          content: resp.data.fine == 0 ? '是否取消订单？' : resp.data.info,
          success: (res) => {
            if (res.confirm) {
              App.doPost({
                uri: '/app/order/action/cancel',
                body: {
                  id: this.data.order.id,
                  memo: '用户取消订单'
                },
                fnSucc: () => {
                  wx.pub("ReloadUserOrderList", {})
                  wx.pub("ReloadUserFin", {})
                  Util.Toast.succ(`取消订单成功`)
                  this.execLoad(this.data.order.id)
                }
              })
            }
          }
        })

      }
    })

  }
})